﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DevExpress.XtraTreeList;
using DevExpress.XtraTreeList.Nodes;
using DevExpress.XtraBars.Docking2010.Views;
using DevExpress.XtraGrid;
using DevExpress.XtraBars.Docking;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraGrid.Columns;
using System.Diagnostics;
using Fcdbas.WinUI.Forms;
using Fcdbas.Core.DataAccess;
using Fcdbas.Core.Xml;
using Fcdbas.Core.Windows;
using Fcdbas.Platform;
using Fcdbas.Core.Reflection;
using System.Reflection;
using Fcdbas.Platform.Properties;
using DevExpress.XtraSplashScreen;
using DevExpress.XtraBars;
using Fcdbas.Platform.Interface;
using Fcdbas.WinUI.Common;
using Fcdbas.WinUI.Design;
using Fcdbas.WinUI.Windows;
using Fcdbas.WinUI.Controls;
using Fcdbas.Platform.Enums;
using Fcdbas.Core;
using Fcdbas.Biz;
using Fcdbas;

namespace Fcdbas.WinUI.Forms
{
    enum emNavType
    {
        TableWindow,
        MastDetail,
        FormWindow
    }

    public partial class frmMainForm : XtraForm, ISalWindow, IView, IMainFormView
    {

        private MainFormPresenter mainFormPresenter;
        private DataItemEnterEventArgs FoucsDataItem;
        private BaseForm currentForm;
        public BaseForm CurrentForm
        {
            get
            {
                return currentForm;
            }
            set
            {
                currentForm = value;
            }
        }
        private IReference _referenceDataItem;
        private DataItem _currentDataItem;
        private object _activeControl;
        public ISalWindow _derived;
        protected SalWindow m_salWindow;
        public List<BarItem> FunctionItems = new List<BarItem>();
        public frmMainForm()
        {

            m_salWindow = new SalWindow(this);
            translate = new WinTranslate("Fcdbas", "Fcdbas", "C", "");
            InitializeComponent();
            //  this.Hide();
            mainFormPresenter = new MainFormPresenter(this);
            tabbedView.DocumentAdded += tabbedView_DocumentAdded;
            tabbedView.DocumentRemoved += tabbedView_DocumentRemoved;
            tabbedView.FloatDocuments.CollectionChanged += tabbedView_FloatDocumentsCollectionChanged;
            this.WindowActions += new WindowActionsEventHandler(frmMainForm_WindowActions);

            Init();
        }
        private void SetTitle()
        {
            this.Text = "运营管理  用户：" + AppEnvironment.Session.USER_ID + "  服务器：" + AppEnvironment.Session.Server + "  数据库：" + AppEnvironment.Session.Database;
        }

        private void Settings()
        {
            bool UserAdditionTools = Fcdbas.Core.Configuration.Config.GetMutilConfig<Boolean>(false, "UserAdditionTools");
            barAttach.Visible = UserAdditionTools;

            bool ShowSysInfo = Fcdbas.Core.Configuration.Config.GetMutilConfig<Boolean>(false, "ShowSysInfo");
            lbMsg.Visible = ShowSysInfo;
            meMsg.Visible = ShowSysInfo;
            if (!ShowSysInfo)
                splitContainerControl1.SplitterPosition = Screen.PrimaryScreen.WorkingArea.Height - 50;
        }
        public event WindowActionsEventHandler WindowActions
        {
            add
            {
                this.m_salWindow.AddWindowActions(value);
            }
            remove
            {
                this.m_salWindow.RemoveWindowActions(value);
            }
        }
        public DialogResult ShowMessage(string msgCode)
        {
            return this.translate.ShowMessage(msgCode);
        }
        /// <summary>
        /// 显示对话框。
        /// </summary>
        /// <param name="msgCode">消息代码</param>
        /// <param name="msgAdd">消息参数，多个参数之间用","分开</param>
        /// <returns>选择结果</returns>
        public DialogResult ShowMessage(string msgCode, string msgAdd)
        {
            return translate.ShowMessage(msgCode, msgAdd);
        }

        public DialogResult ShowMessage(string msgCode, string msgAdd, MessageBoxButtons btnType)
        {
            return translate.ShowMessage(msgCode, msgAdd, btnType);
        }
        public DialogResult ShowMessage(string msgCode, string msgAdd, MessageBoxButtons btnType, MessageBoxIcon iconType)
        {
            return translate.ShowMessage(msgCode, msgAdd, btnType, iconType);
        }
        public DialogResult ShowMessage(string msgCode, string msgAdd, MessageBoxButtons btnType, MessageBoxIcon iconType, MessageBoxDefaultButton defaultType)
        {
            return translate.ShowMessage(this, msgCode, msgAdd, btnType, iconType, defaultType);
        }
        public DialogResult ShowMessage(IWin32Window owner, string msgCode, string msgAdd, MessageBoxButtons buttonsType, MessageBoxIcon iconType, MessageBoxDefaultButton defaultButton)
        {
            return translate.ShowMessage(owner, msgCode, msgAdd, buttonsType, iconType, defaultButton);
        }
        public WinTranslate translate;
        public object Derived
        {
            get { return _derived; }
        }
        public void SetStatus(string msg)
        {
            this.barStatus.Caption = msg;
        }
        public void AttachMessageActions(ISalWindow target)
        {
            this.m_salWindow.AddWindowActions(target);
        }

        public void DefaultWndProc(ref Message m)
        {
            base.WndProc(ref m);
        }

        public SalWindow GetSalWindowImpl()
        {
            return this.m_salWindow;
        }

        public int GetWindowType()
        {
            return 1;
        }
        void frmMainForm_WindowActions(object sender, WindowActionsEventArgs e)
        {
            switch (e.ActionType)
            {
                case Const.AM_DataSourceFieldModified:
                    iSave.Enabled = true;
                    break;
                case Const.AM_DataSourceMarkRollback:
                    iSave.Enabled = false;
                    break;
            }
        }
        void tabbedView_DocumentAdded(object sender, DocumentEventArgs e)
        {
            RegisterDocument(e.Document);
        }

        void tabbedView_DocumentRemoved(object sender, DocumentEventArgs e)
        {
            UnregisterDocument(e.Document);
            if (Documents.Values.Count == 0)
            {
                DockPanel dp = GetTopDockPanel(dockPanelApproval);
                dp.Hide();
                // iApproval.Enabled = false;
                //tblRouting.DataSource = null;
                //tblRouting.RefreshDataSource();
                cbQueryList.Items.Clear();
            }
        }
        void RegisterDocument(BaseDocument document)
        {
            Documents.Add(document.Form.Tag, document);
        }
        void UnregisterDocument(BaseDocument document)
        {
            if (document.Form != null)
                Documents.Remove(document.Form.Tag);

            // tabbedView.Documents.Remove(document);
        }
        void tabbedView_FloatDocumentsCollectionChanged(DevExpress.XtraBars.Docking2010.Base.CollectionChangedEventArgs<BaseDocument> ea)
        {
            if (ea.ChangedType == DevExpress.XtraBars.Docking2010.Base.CollectionChangedType.ElementAdded)
                RegisterDocument(ea.Element);
            if (ea.ChangedType == DevExpress.XtraBars.Docking2010.Base.CollectionChangedType.ElementRemoved)
                UnregisterDocument(ea.Element);
        }
        IDictionary<object, BaseDocument> documentsCore = new Dictionary<object, BaseDocument>();
        public IDictionary<object, BaseDocument> Documents
        {
            get { return documentsCore; }
        }
        private void Init()
        {
            SplashScreenManager.Default.SendCommand(LoadStatus.ShowProgress, "加载本地资源");
            DevExpress.Accessibility.AccLocalizer.Active = new DevExpress.LocalizationCHS.DevExpressUtilsLocalizationCHS();
            DevExpress.XtraBars.Localization.BarLocalizer.Active = new DevExpress.LocalizationCHS.DevExpressXtraBarsLocalizationCHS();
            //DevExpress.XtraCharts.Localization.ChartLocalizer.Active = new DevExpress.LocalizationCHS.DevExpressXtraChartsLocalizationCHS();
            DevExpress.XtraEditors.Controls.Localizer.Active = new DevExpress.LocalizationCHS.DevExpressXtraEditorsLocalizationCHS();
            DevExpress.XtraGrid.Localization.GridLocalizer.Active = new DevExpress.LocalizationCHS.DevExpressXtraGridLocalizationCHS();
            DevExpress.XtraLayout.Localization.LayoutLocalizer.Active = new DevExpress.LocalizationCHS.DevExpressXtraLayoutLocalizationCHS();
            DevExpress.XtraNavBar.NavBarLocalizer.Active = new DevExpress.LocalizationCHS.DevExpressXtraNavBarLocalizationCHS();
            //  DevExpress.XtraPivotGrid.Localization.PivotGridLocalizer.Active = new DevExpress.LocalizationCHS.DevExpressXtraPivotGridLocalizationCHS();
            DevExpress.XtraPrinting.Localization.PreviewLocalizer.Active = new DevExpress.LocalizationCHS.DevExpressXtraPrintingLocalizationCHS();

            DevExpress.XtraRichEdit.Localization.XtraRichEditLocalizer.Active = new DevExpress.LocalizationCHS.DevExpressXtraRichEditLocalizationCHS();
            DevExpress.XtraRichEdit.Localization.RichEditExtensionsLocalizer.Active = new DevExpress.LocalizationCHS.DevExpressXtraRichEditExtensionsLocalizationCHS();

            //DevExpress.XtraScheduler.Localization.SchedulerLocalizer.Active = new DevExpress.LocalizationCHS.DevExpressXtraSchedulerLocalizationCHS();
            //DevExpress.XtraScheduler.Localization.SchedulerExtensionsLocalizer.Active = new DevExpress.LocalizationCHS.DevExpressXtraSchedulerExtensionsLocalizationCHS();
            //DevExpress.XtraSpellChecker.Localization.SpellCheckerLocalizer.Active = new DevExpress.LocalizationCHS.DevExpressXtraSpellCheckerLocalizationCHS();
            DevExpress.XtraTreeList.Localization.TreeListLocalizer.Active = new DevExpress.LocalizationCHS.DevExpressXtraTreeListLocalizationCHS();

            tvNavigator.BackColor = Color.Transparent;
            tvNavigator.Appearance.Empty.BackColor = Color.Transparent;
            //tvNavigator.Appearance.Empty.BackColor2 = Color.Transparent;
            tvNavigator.Appearance.EvenRow.BackColor = Color.Transparent;
            //tvNavigator.Appearance.EvenRow.BackColor2 = Color.Transparent;
            tvNavigator.Appearance.Empty.BackColor = System.Drawing.Color.Transparent;
            tvNavigator.Appearance.EvenRow.BackColor = System.Drawing.Color.Transparent;
            tvNavigator.Appearance.FilterPanel.BackColor = System.Drawing.Color.Transparent;
            tvNavigator.Appearance.FixedLine.BackColor = System.Drawing.Color.Transparent;
            tvNavigator.Appearance.FooterPanel.BackColor = System.Drawing.Color.Transparent;
            tvNavigator.Appearance.GroupButton.BackColor = System.Drawing.Color.Transparent;
            tvNavigator.Appearance.GroupFooter.BackColor = System.Drawing.Color.Transparent;
            tvNavigator.Appearance.HeaderPanel.BackColor = System.Drawing.Color.Transparent;
            //tvNavigator.Appearance.HideSelectionRow.BackColor = System.Drawing.Color.Transparent;
            tvNavigator.Appearance.HorzLine.BackColor = System.Drawing.Color.Transparent;
            //tvNavigator.Appearance.OddRow.BackColor = System.Drawing.Color.Transparent;
            //tvNavigator.Appearance.Preview.BackColor = System.Drawing.Color.Transparent;
            tvNavigator.Appearance.Row.BackColor = System.Drawing.Color.Transparent;
            //tvNavigator.Appearance.SelectedRow.BackColor = System.Drawing.Color.Transparent;
            tvNavigator.Appearance.TreeLine.BackColor = System.Drawing.Color.Transparent;
            tvNavigator.Appearance.VertLine.BackColor = System.Drawing.Color.Transparent;
            meMsg.Font = new Font(AppEnvironment.AppOption.FontName, AppEnvironment.AppOption.FontSize);
            this.tvNavigator.Appearance.Row.Font = new Font(AppEnvironment.AppOption.FontName, AppEnvironment.AppOption.FontSize);
            this.tvNavigator.Columns[0].AppearanceHeader.Font = new Font(AppEnvironment.AppOption.FontName, AppEnvironment.AppOption.FontSize);
            this.tvNavigator.Appearance.OddRow.Font = new Font(AppEnvironment.AppOption.FontName, AppEnvironment.AppOption.FontSize);
            this.tvNavigator.Appearance.EvenRow.Font = new Font(AppEnvironment.AppOption.FontName, AppEnvironment.AppOption.FontSize);
            tvNavigator.FocusedNodeChanged += new FocusedNodeChangedEventHandler(tvNavigator_FocusedNodeChanged);
            tvNavigator.ClearNodes();
            foreach (BarItem bi in this.barManager1.Items)
            {
                //bi.ItemAppearance.Normal.Font = new Font(AppEnvironment.AppOption.FontName, AppEnvironment.AppOption.FontSize);
                //bi.ItemAppearance.Hovered.Font = new Font(AppEnvironment.AppOption.FontName, AppEnvironment.AppOption.FontSize);
                //bi.ItemAppearance.Pressed.Font = new Font(AppEnvironment.AppOption.FontName, AppEnvironment.AppOption.FontSize);
                bi.ItemAppearance.SetFont(new Font(AppEnvironment.AppOption.FontName, AppEnvironment.AppOption.FontSize));
                if (bi is BarButtonItem)
                    FunctionItems.Add(bi);
            }
            foreach (BarItem bi in FunctionItems)
            {
                AddUserFunction(bi.Name, SecObjectType.Button, bi.Caption, UpdatesSql.Standard);
            }
            SplashScreenManager.Default.SendCommand(LoadStatus.ShowProgress, "加载导航");
            mainFormPresenter.DisplayNavigator();
            mainFormPresenter.DisplayRecentModule();
            this.tvNavigator.Columns[0].OptionsColumn.AllowEdit = false;
            // mainFormPresenter.DisplayFavModule();
            this.iSave.Enabled = false;
            if (!string.IsNullOrEmpty(AppEnvironment.AppOption.DefaultHome))
                OpenModule(AppEnvironment.AppOption.DefaultHome, "");


            LoadSystemOption();

            SplashScreenManager.Default.SendCommand(LoadStatus.ShowProgress, "加载用户中心");
            bool OpenUserCenter = Fcdbas.Core.Configuration.Config.GetMutilConfig<Boolean>(false, "OpenUserCenter");
            if (OpenUserCenter)
                LoadWorkCenter();
            DevExpress.XtraBars.Helpers.SkinHelper.InitSkinPopupMenu(iPaintStyle);
            // string skinName = DevExpress.LookAndFeel.UserLookAndFeel.Default.ActiveSkinName;
            //DevExpress.LookAndFeel.ActiveLookAndFeelStyle style = DevExpress.LookAndFeel.UserLookAndFeel.Default.ActiveStyle;
            DevExpress.LookAndFeel.UserLookAndFeel.Default.SetSkinStyle(mainFormPresenter.UserSkin.info);
            //  DevExpress.LookAndFeel.DefaultLookAndFeel laf = new DevExpress.LookAndFeel.DefaultLookAndFeel();
            // laf.LookAndFeel.SetStyle(
            SplashScreenManager.Default.SendCommand(LoadStatus.ShowProgress, "加载完成，正在进入系统");
            SplashScreenManager.CloseForm(false);
        }

        private void frmMainForm_Load(object sender, EventArgs e)
        {

            //   this.Font = new Font(AppEnvironment.AppOption.FontName, AppEnvironment.AppOption.FontSize);
            // GetTopDockPanel(this.dockPanelApproval).Hide();
            //   GetTopDockPanel(dockPanelTask).Hide();
            //  GetTopDockPanel(dockPanelMessage).Hide();
            //  GetTopDockPanel(dockPanelDoc).Hide();
            //  GetTopDockPanel(dockPanelNote).Hide();

            //  this.Show();
            Settings();
            SetTitle();
        }
        private void LoadSystemOption()
        {
            this.timerAlarm.Enabled = AppEnvironment.AppOption.AlarmEnable;
            this.timerAlarm.Interval = AppEnvironment.AppOption.AlarmRiseTime * 1000;
        }
        protected void AddUserFunction(string secObject, string subType, string desc, UpdatesSql update)
        {
            if (!AppEnvironment.Session.IsRoot)
                return;
            string forceRd = "False";
            if (update == UpdatesSql.ReadOnly)
                forceRd = "True";
            fnd_object_security objSec = FndObjectFactory.CreateObjectSecurity(this.GetType(), secObject, SecObjectType.Client, subType, desc, forceRd);
            if (FndDAL.FindObjectSecurity(objSec) == null)
            {
                FndDAL.ObjectSecurityNew(objSec);
            }
        }
        private void LoadTask()
        {
            var form = mainFormPresenter.LoadForm("App.Person.Task.dll", "App.Person.Task.frmMyTodoItems");
            form.MainForm = this;
            form.TopLevel = false;
            form.Dock = DockStyle.Fill;
            form.FormBorderStyle = FormBorderStyle.None;

            this.dockPanelTask.Controls.Add(form);
            this.dockPanelTask.Text = form.Text;
            form.Show();
            GetTopDockPanel(dockPanelTask).Show();
        }
        private void LoadMessage()
        {
            var form = mainFormPresenter.LoadForm("App.Person.Message.dll", "App.Person.Message.Forms.frmPersonCentor");
            form.MainForm = this;
            form.TopLevel = false;
            form.Dock = DockStyle.Fill;
            form.FormBorderStyle = FormBorderStyle.None;
            this.dockPanelMessage.Text = form.Text;
            this.dockPanelMessage.Controls.Add(form);

            form.Show();
            GetTopDockPanel(dockPanelMessage).Show();
        }
        private void LoadDocument()
        {
            var form = mainFormPresenter.LoadForm("App.Docman.Base.dll", "App.Docman.Base.frmDocObject");
            form.MainForm = this;
            form.TopLevel = false;
            form.Dock = DockStyle.Fill;
            form.FormBorderStyle = FormBorderStyle.None;

            this.dockPanelDoc.Controls.Add(form);
            this.dockPanelDoc.Text = form.Text;
            form.Show();
            GetTopDockPanel(dockPanelDoc).Show();
        }
        private void LoadNote()
        {
            var form = mainFormPresenter.LoadForm("App.Person.Notes.dll", "App.Person.Notes.frmFndNoteBook");
            form.MainForm = this;
            form.TopLevel = false;
            form.Dock = DockStyle.Fill;
            form.FormBorderStyle = FormBorderStyle.None;
            form.Opacity = 0.5;
            this.dockPanelNote.Controls.Add(form);
            this.dockPanelNote.Text = form.Text;
            form.Show();
            GetTopDockPanel(dockPanelNote).Show();
        }
        protected void ShowModule(BaseForm baseForm)
        {
            if (baseForm is cDialogWindow)
            {
                currentForm = baseForm;
                baseForm.MainForm = this;
                baseForm.ShowDialog(this);
                return;
            }
            currentForm = baseForm;
            baseForm.IsMdiContainer = false;
            baseForm.MainForm = this;
            baseForm.MdiParent = this;
            baseForm.DataItemEnter += new EventHandler<WinUI.Common.DataItemEnterEventArgs>(baseForm_DataItemEnter);
            baseForm.SaveCompleted += new EventHandler<EventArgs>(baseForm_SaveCompleted);
            baseForm.MasterCurrentChanged += new EventHandler<EventArgs>(baseForm_MasterCurrentChanged);
            //baseForm.MasterdataSourceBinding.DataSourceDataChanged += new EventHandler<cDataSource.ReturnEventArgsSalBoolean>(MasterdataSourceBinding_DataSourceDataChanged);
            baseForm.Show();
            if (baseForm.ShowQuery)
            {
                SplashScreenManager.CloseForm(false);
                string where = baseForm.CurrentSourceBinding.OnDataIsQueryingWhere(baseForm);
                BaseForm queryForm = new frmQuery(baseForm, baseForm.UQProfile, 0, where, baseForm.GetCurrentDSGrid());
                queryForm.ShowDialog();
                LoadUserQuery(baseForm.UQProfile);
            }
            baseForm.SetMainFunction();
            //if (currentForm != null && currentForm.CurrentSourceBinding != null)
            //{
            //    if (!currentForm.CurrentSourceBinding.AllowNew || currentForm.CurrentSourceBinding.Updates == Platform.Enums.UpdatesSql.ReadOnly)
            //        iNewRecord.Enabled = false;
            //    else
            //        iNewRecord.Enabled = currentForm.IsDataSourceNew();
            //    if (!currentForm.CurrentSourceBinding.AllowRemove || currentForm.CurrentSourceBinding.Updates == Platform.Enums.UpdatesSql.ReadOnly)
            //        iDelete.Enabled = false;
            //    else
            //        iDelete.Enabled = currentForm.IsDataSourceDelete();
            //}

        }
        public void OpenModule(Biz.fnd_exp_navigator nav)
        {
            if (nav.key_type == mainFormPresenter.NVA_TYPE_PARENT)
                return;
            BaseDocument document = null;
            if (!Documents.TryGetValue(nav.nav_key, out document))
            {
                SplashScreenManager.ShowForm(this, typeof(dlgWaitForm), true, true, false);
                //SplashScreenManager.Default.ShowWaitForm();
                try
                {
                    SplashScreenManager.Default.SetWaitFormCaption("打开模块");
                    SplashScreenManager.Default.SetWaitFormDescription("正在打开模块，请稍候！");
                }
                catch (Exception ex)
                {
                }
                Fcdbas.Core.Log.XTrace.WriteLine("TEST:生成模块！！！！");
                BaseForm baseForm = null;
                try
                {
                    baseForm = mainFormPresenter.OpenModule(nav);
                }
                catch (Exception ex)
                {
                    SplashScreenManager.CloseForm(false);
                    this.ShowMessage("系统错误，请联系系统管理员，错误内容：" + ex.Message);
                    return;
                }
                if (baseForm == null)
                {
                    SplashScreenManager.CloseForm(false);
                    return;
                }
                baseForm.Tag = nav.nav_key;
                GetNavMsg(nav);
                baseForm.NavMsg = this.navMsg;
                try
                {
                    ShowModule(baseForm);
                }
                catch (Exception ex)
                {
                    SplashScreenManager.CloseForm(false);
                    this.ShowMessage("系统错误，请联系系统管理员，错误内容：" + ex.Message);

                    return;
                }
                if (tabbedView.Documents.TryGetValue(baseForm, out document))
                {
                    document.Caption = nav.win_text;
                    document.Tag = nav;
                }
                SplashScreenManager.CloseForm(false);
            }
            else tabbedView.Controller.Activate(document);
        }

        //void MasterdataSourceBinding_DataSourceDataChanged(object sender, cDataSource.ReturnEventArgsSalBoolean e)
        //{
        //    if (DataSourceDataChanged != null)
        //        DataSourceDataChanged.Invoke(sender, EventArgs.Empty);
        //}

        void baseForm_MasterCurrentChanged(object sender, EventArgs e)
        {
            if (DataSourceDataChanged != null)
                DataSourceDataChanged.Invoke(sender, EventArgs.Empty);
            //LoadApproval_routing();
        }
        /// <summary>
        /// 根据模块KEY和条件打开指定的模块
        /// </summary>
        /// <param name="nav_key">模块Key</param>
        /// <param name="sqlWhere">条件</param>
        /// <returns></returns>
        public BaseForm OpenModule(string nav_key, string sqlWhere, bool useProfile = true, bool isCreateByOth = false)
        {
            Fcdbas.Biz.fnd_exp_navigator nav = MainFormPresenter.FindNavigator(nav_key);
            if (nav == null)
            {
                this.ShowMessage("没有找到指定的模块，请详细检查！Nav_KEY：" + nav_key, "", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return null;
            }
            if (nav.key_type == mainFormPresenter.NVA_TYPE_PARENT)
                return null;
            BaseDocument document = null;
            BaseForm baseForm = null;
            if (!Documents.TryGetValue(nav.nav_key, out document))
            {
                SplashScreenManager.ShowForm(this, typeof(dlgWaitForm), true, true, false);
                try
                {

                    baseForm = mainFormPresenter.OpenModule(nav);
                }
                catch (Exception ex)
                {
                    SplashScreenManager.CloseForm(false);
                    this.ShowMessage("系统错误，请联系系统管理员，错误内容：" + ex.Message);
                    return null;
                }
                if (baseForm == null)
                {
                    SplashScreenManager.CloseForm(false);
                    return null;
                }

                //SplashScreenManager.Default.ShowWaitForm();
                try
                {
                    SplashScreenManager.Default.SetWaitFormCaption("打开模块");
                    SplashScreenManager.Default.SetWaitFormDescription("正在打开模块，请稍候！");
                }
                catch (Exception ex)
                {
                }
                GetNavMsg(nav);
                baseForm.NavMsg = navMsg;
                baseForm.Tag = nav.nav_key;
                baseForm.UseProfile = useProfile;
                baseForm.IsCreateByOth = isCreateByOth;
                baseForm.MasterdataSourceBinding.UserWhere = sqlWhere;
                try
                {
                    ShowModule(baseForm);
                }
                catch (Exception ex)
                {
                    SplashScreenManager.CloseForm(false);
                    this.ShowMessage("系统错误，请联系系统管理员，错误内容：" + ex.Message);

                    return baseForm;
                }
                if (tabbedView.Documents.TryGetValue(baseForm, out document))
                {
                    document.Caption = nav.win_text;
                    document.Tag = nav;
                }
                SplashScreenManager.CloseForm(false);
            }
            else
            {

                baseForm = document.Control as BaseForm;
                if (isCreateByOth)
                {
                    if (baseForm.Save)
                    {
                        if (this.ShowMessage(this, "当前数据未保存，是否继续？", "", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) == System.Windows.Forms.DialogResult.Yes)
                        {
                            baseForm.MasterdataSourceBinding.UserWhere = sqlWhere;
                            baseForm.MasterdataSourceBinding.DataSourcePopulate(DataSourcePopulate.All);
                        }
                    }
                    else
                    {
                        baseForm.MasterdataSourceBinding.UserWhere = sqlWhere;
                        baseForm.MasterdataSourceBinding.DataSourcePopulate(DataSourcePopulate.All);
                    }
                }
                tabbedView.Controller.Activate(document);
            }
            return baseForm;
        }

        void baseForm_SaveCompleted(object sender, EventArgs e)
        {
            SetToolbarEnable(true);
            iSave.Enabled = false;
            if (currentForm == null || currentForm.CurrentSourceBinding == null || currentForm.CurrentSourceBinding.LogicalParent == null || currentForm.CurrentSourceBinding.LogicalParent.Current == null)
                return;
            IEntity cn = currentForm.CurrentSourceBinding.LogicalParent.Current as IEntity;
            if (cn.Status == RecordStatus.Normal && !(currentForm.CurrentSourceBinding.LogicalParent.DataSource is IEntity))
            {

                if (currentForm.CurrentSourceBinding.OldUpdate == UpdatesSql.Standard)
                {

                    currentForm.CurrentSourceBinding.Updates = UpdatesSql.Standard;
                    currentForm.SetControlReadOnly(currentForm, currentForm.CurrentSourceBinding);
                }
            }

        }
        private void DispDSBInfo(DataSourceBinding dsb)
        {
            if (dsb == null)
                return;
            string msg = "DS Name: " + dsb.Name + Environment.NewLine;
            msg += "Component: " + dsb.Module + Environment.NewLine;
            msg += "Logical Unit: " + dsb.LogicalUnit + Environment.NewLine;
            msg += "View: " + dsb.ViewName + Environment.NewLine;
            msg += "Package: " + dsb.PackageName + Environment.NewLine;
            if (dsb.LogicalParent != null)
                msg += "Logical Parent: " + dsb.LogicalParent.LogicalUnit + Environment.NewLine;
            msg = currentForm.NavMsg + Environment.NewLine + msg;
            meMsg.Text = msg;
        }
        private DataSourceBinding prevDS = null;
        public event EventHandler<DataSourceEventArgs> DataSourceChanged;
        public event EventHandler<EventArgs> DataSourceDataChanged;
        public void SetToolbarEnable(bool enable)
        {
            this.iPaste.Enabled = enable;
            // this.iCopy.Enabled = enable;
            this.iRefresh.Enabled = enable;
            // this.iDelete.Enabled = enable;
            this.iFront.Enabled = enable;
            this.iNext.Enabled = enable;
            if (enable)
            {
                if (!currentForm.CurrentSourceBinding.AllowRemove || currentForm.CurrentSourceBinding.Updates == Platform.Enums.UpdatesSql.ReadOnly || currentForm.CurrentSourceBinding.DataSource is IEntity)
                    iDelete.Enabled = false;
                else
                    iClear.Enabled = iDelete.Enabled = currentForm.IsDataSourceDelete();
            }
            else
                this.iDelete.Enabled = false;
            if (enable)
            {
                if (currentForm.CurrentSourceBinding.DataSource is IEntity || currentForm.CurrentSourceBinding.DataSource == null)
                {
                    //iRefresh.Enabled = iCopy.Enabled = false;
                    iCopy.Enabled = false;
                    if (currentForm.CurrentSourceBinding.AllowNew && currentForm.CurrentSourceBinding.Updates != Platform.Enums.UpdatesSql.ReadOnly)
                    {
                        iNewRecord.Enabled = iClear.Enabled = true;
                    }
                }
                else if (!currentForm.CurrentSourceBinding.AllowNew || currentForm.CurrentSourceBinding.Updates == Platform.Enums.UpdatesSql.ReadOnly)
                {
                    iNewRecord.Enabled = iCopy.Enabled = iClear.Enabled = false;

                }
                else
                    iRefresh.Enabled = iCopy.Enabled = iNewRecord.Enabled = iClear.Enabled = currentForm.IsDataSourceNew();
            }
            else
            {
                if (currentForm.CurrentSourceBinding.AllowNew && currentForm.CurrentSourceBinding.Updates != Platform.Enums.UpdatesSql.ReadOnly)
                {
                    iRefresh.Enabled = iNewRecord.Enabled = iClear.Enabled = true;
                }
                else
                    iNewRecord.Enabled = false;
                this.iDelete.Enabled = iCopy.Enabled = iClear.Enabled = enable;
            }
            SetToolbarEnableWithParent();
        }
        public void SetNewRecordEnable()
        {
            if (currentForm != null && currentForm.CurrentSourceBinding != null)
            {
                if (!currentForm.CurrentSourceBinding.AllowRemove || currentForm.CurrentSourceBinding.Updates == Platform.Enums.UpdatesSql.ReadOnly || currentForm.CurrentSourceBinding.DataSource is IEntity)
                    iDelete.Enabled = iClear.Enabled = false;
                else
                    iRefresh.Enabled = iDelete.Enabled = iClear.Enabled = currentForm.IsDataSourceDelete();
                if (!currentForm.CurrentSourceBinding.AllowNew || currentForm.CurrentSourceBinding.Updates == Platform.Enums.UpdatesSql.ReadOnly)
                    iCopy.Enabled = iNewRecord.Enabled = iClear.Enabled = false;
                else
                {

                    iRefresh.Enabled = iCopy.Enabled = iNewRecord.Enabled = currentForm.IsDataSourceNew();
                    if (currentForm.CurrentSourceBinding.DataSource is IEntity || currentForm.CurrentSourceBinding.DataSource == null)
                        iCopy.Enabled = iDelete.Enabled = iClear.Enabled = false;

                }
                SetToolbarEnableWithParent();
            }
        }
        /// <summary>
        /// 根据父单元设置detail是否可以增删改
        /// </summary>
        public void SetToolbarEnableWithParent()
        {
            if (currentForm == null || currentForm.CurrentSourceBinding == null || currentForm.CurrentSourceBinding.LogicalParent == null || currentForm.CurrentSourceBinding.LogicalParent.Current == null)
                return;
            IEntity cn = currentForm.CurrentSourceBinding.LogicalParent.Current as IEntity;
            if (cn.Status != RecordStatus.Normal || currentForm.CurrentSourceBinding.LogicalParent.DataSource is IEntity)
            {
                iCopy.Enabled = iNewRecord.Enabled = iDelete.Enabled = iClear.Enabled = false;
                if (currentForm.CurrentSourceBinding.Updates == UpdatesSql.Standard && cn.Status != RecordStatus.Normal)
                {
                    currentForm.CurrentSourceBinding.OldUpdate = UpdatesSql.Standard;
                    currentForm.CurrentSourceBinding.Updates = UpdatesSql.ReadOnly;
                    currentForm.SetControlReadOnly(currentForm, currentForm.CurrentSourceBinding);
                }
            }
            else
            {

                currentForm.CurrentSourceBinding.Updates = currentForm.CurrentSourceBinding.OldUpdate;
                if (currentForm.CurrentSourceBinding.AllowNew && currentForm.CurrentSourceBinding.Updates != Platform.Enums.UpdatesSql.ReadOnly)
                {
                    iNewRecord.Enabled = iCopy.Enabled = iRefresh.Enabled = iDelete.Enabled = iClear.Enabled = true;
                }
                else
                    iNewRecord.Enabled = iCopy.Enabled = iClear.Enabled = false;
                currentForm.SetControlReadOnly(currentForm, currentForm.CurrentSourceBinding);
            }
        }
        void baseForm_DataItemEnter(object sender, WinUI.Common.DataItemEnterEventArgs e)
        {
            if (currentForm == null || currentForm.CurrentSourceBinding == null)
            {
                SetToolbarEnable(false);
                return;
            }
            if (sender is BaseForm)
            {
                BaseForm frm = sender as BaseForm;
                if (frm != null)
                    currentForm = frm;
            }
            if (prevDS == null)
            {
                if (DataSourceChanged != null)
                {
                    DataSourceChanged.Invoke(currentForm, new DataSourceEventArgs(currentForm.CurrentSourceBinding));

                    LoadUserQuery(currentForm.UQProfile);
                }
                prevDS = currentForm.CurrentSourceBinding;

            }
            else
            {
                if (!prevDS.Equals(currentForm.CurrentSourceBinding))
                {
                    if (DataSourceChanged != null)
                    {
                        DataSourceChanged.Invoke(currentForm, new DataSourceEventArgs(currentForm.CurrentSourceBinding));

                        LoadUserQuery(currentForm.UQProfile);
                    }

                }
            }
            DispDSBInfo(currentForm.CurrentSourceBinding);
            if (currentForm.CurrentSourceBinding.LogicalParent == null)
            {
                iRefresh.Enabled = currentForm.IsAvaliable(iRefresh.Name);
            }
            else
            {
                iRefresh.Enabled = false;
            }
            
            _currentDataItem = e.DItem;
            _referenceDataItem = null;
            _activeControl = e.Control;
            this.FoucsDataItem = e;
            if (currentForm == null) return;
            // LoadApproval_routing();

            if (e.DItem != null && !string.IsNullOrEmpty(e.DItem.Reference))
            {
                iZoom.Enabled = Security.IsPresObjAvaliable(AppEnvironment.Session.USER_ID, e.DItem.Reference, "", SecObjectType.Zoom);
            }
            else
            {
                iZoom.Enabled = false;
            }
            // GetApprovalEnable(currentForm.CurrentSourceBinding);
            if (e.Control is IReference)
            {
                IReference referenceControl = ((IReference)e.Control);
                if (referenceControl.IsReference)
                {

                    // iValueList.Enabled = true;
                    _referenceDataItem = ((IReference)e.Control);

                }
            }
            IEntity en = currentForm.CurrentSourceBinding.Current as IEntity;
            if (en == null)
            {
                SetToolbarEnable(false);
                return;
            }
            else
            {
                SetToolbarEnable(true);
            }
            //if (currentForm.CurrentSourceBinding != null)
            //{
            //    if (!currentForm.CurrentSourceBinding.AllowNew || currentForm.CurrentSourceBinding.Updates == Platform.Enums.UpdatesSql.ReadOnly)
            //        this.iDelete.Enabled = iCopy.Enabled = iNewRecord.Enabled = false;
            //    else
            //        iCopy.Enabled = iNewRecord.Enabled = currentForm.IsDataSourceNew();

            //}
            //如果返回为FALSE(Boolean类型), 那么就算设置了Lov,也会是灰色,不可以使用
            SalBoolean vEnable = currentForm.OnDataItemLovInquire(e.DItem);
            if (!vEnable)
            {
                iValueList.Enabled = vEnable;
                return;
            }
            if (_activeControl is IReadOnly)
            {

                if (e.DItem != null && e.DItem.LogicalParent != null && (!((IReadOnly)_activeControl).ReadOnly || en.Status == RecordStatus.New))
                {
                    iValueList.Enabled = Security.IsAuthorize(AppEnvironment.Session.USER_ID, currentForm.GetType().FullName, e.DItem.LogicalParent.SubstringRight("."), SecObjectType.LOV);
                }
                else
                {
                    iValueList.Enabled = false;
                }
            }
            if (_activeControl is GridColumn)
            {
                GridColumn gcolumn = _activeControl as GridColumn;
                if ((e.DItem.LogicalParent != null) && (!gcolumn.OptionsColumn.ReadOnly || en.Status == RecordStatus.New))
                {
                    iValueList.Enabled = Security.IsAuthorize(AppEnvironment.Session.USER_ID, currentForm.GetType().FullName, e.DItem.LogicalParent.SubstringRight("."), SecObjectType.LOV);
                }
                else
                {
                    iValueList.Enabled = false;
                }
            }

        }
        private TreeListNode FavNode;
        public void DisplayNavigatorView(List<Biz.fnd_exp_navigator> navs)
        {
            if (navs == null)
                return;

            //tvNavigator.Nodes.Clear();
            //TreeListNode rootNode = tvNavigator.AppendNode(new object[] { "Fcdbas" }, 5);
            //rootNode.HasChildren = true;
            //rootNode.ImageIndex = 0;
            //var parent = from p in navs
            //             where p.key_type == NVA_TYPE_PARENT && string.IsNullOrEmpty(p.parent_key)
            //             select p;
            //foreach (var p in parent)
            //{
            //    AddNodeToTreeView(navs, p, rootNode);
            //}

            tvNavigator.Nodes.Clear();
            TreeListNode rootNode = tvNavigator.AppendNode(new object[] { "应用程序", null, null, 5 }, null);
            DisplayNavigatorViewByType(navs, "A", rootNode);

            // rootNode.ExpandAll();
            TreeListNode rootNode2 = tvNavigator.AppendNode(new object[] { "系统管理", null, null, 5 }, null);
            DisplayNavigatorViewByType(navs, "M", rootNode2);

            TreeListNode rootNode3 = tvNavigator.AppendNode(new object[] { "个人中心", null, null, 5 }, null);
            DisplayNavigatorViewByType(navs, "P", rootNode3);
            FavNode = tvNavigator.AppendNode(new object[] { "个人收藏", null, null, 5 }, null);
            FavNode.Tag = "个人收藏";
            mainFormPresenter.DisplayFavModule();
            ////TreeListNode rootNode = tvNavigator.AppendNode(new object[] { "Fcdbas" }, 5);
            ////rootNode.HasChildren = true;
            ////rootNode.ImageIndex = 0;

            //var parent = from p in navs
            //             where p.key_type == NVA_TYPE_PARENT && string.IsNullOrEmpty(p.parent_key)
            //             select p;
            //foreach (var p in parent)
            //{
            //    AddNodeToTreeView(navs, p, rootNode);
            //    //if (p.key_type == NVA_TYPE_PARENT)
            //    //{
            //    //    TreeListNode tlPerson5 = tvNavigator.AppendNode(new object[] { "Properties.Resources.OwnerName", null, null, 6 }, rootNode);
            //    //}
            //}
            //tvNavigator.ExpandAll();
        }
        private void DisplayNavigatorViewByType(List<Biz.fnd_exp_navigator> navs, string nav_class, TreeListNode rootNode)
        {
            var parent = from p in navs
                         where p.key_type == mainFormPresenter.NVA_TYPE_PARENT && string.IsNullOrEmpty(p.parent_key) && p.navi_class == nav_class
                         select p;
            foreach (var p in parent)
            {
                AddNodeToTreeView(navs, p, rootNode);
                //if (p.key_type == NVA_TYPE_PARENT)
                //{
                //    TreeListNode tlPerson5 = tvNavigator.AppendNode(new object[] { "Properties.Resources.OwnerName", null, null, 6 }, rootNode);
                //}
            }
        }
        /// <summary>
        /// 递归增加
        /// </summary>
        /// <param name="navs"></param>
        /// <param name="nav"></param>
        /// <param name="node"></param>
        private void AddNodeToTreeView(List<Biz.fnd_exp_navigator> navs, Biz.fnd_exp_navigator nav, TreeListNode node)
        {
            if (nav.key_type == mainFormPresenter.NVA_TYPE_PARENT)
            {
                TreeListNode cd = tvNavigator.AppendNode(new object[] { nav.win_text, null, null, 1 }, node, nav);
                //TreeListNode cd = tvNavigator.AppendNode(new object[] { nav.win_text }, node, nav);
                //cd.HasChildren = true;
                //cd.ImageIndex = 6;
                //cd.SelectImageIndex = 3;

                var parent = from p in navs
                             where p.parent_key == nav.nav_key
                             select p;
                foreach (var p in parent)
                {
                    AddNodeToTreeView(parent.ToList(), p, cd);
                }
            }
            else
            {
                //TreeListNode cd = tvNavigator.AppendNode(new object[] { nav.win_text, null, null, 7 }, node, nav);
                if (mainFormPresenter.IsAvaliable(nav.pres_object))
                {
                    TreeListNode cd = tvNavigator.AppendNode(new object[] { nav.win_text }, node, nav);
                    if (nav.nav_type == emNavType.FormWindow.ToString())
                        cd.ImageIndex = 9;
                    else if (nav.nav_type == emNavType.MastDetail.ToString())
                        cd.ImageIndex = 4;
                    else
                        cd.ImageIndex = 7;
                    cd.SelectImageIndex = 3;
                }
            }
        }
        private string navMsg = "";
        private void tvNavigator_FocusedNodeChanged(object sender, FocusedNodeChangedEventArgs e)
        {
            if (e.Node == null || e.Node.Tag == null)
                return;
            Biz.fnd_exp_navigator nav = e.Node.Tag as Biz.fnd_exp_navigator;
            if (nav == null)
                return;
            // OpenModule(nav);
            GetNavMsg(nav);
        }
        private void GetNavMsg(Biz.fnd_exp_navigator nav)
        {
            meMsg.Text = "";
            string msg = "Key: " + nav.nav_key + Environment.NewLine;
            msg += "Name: " + nav.nav_name + Environment.NewLine;
            msg += "Object: " + nav.pres_object + Environment.NewLine;
            // msg += "Type: " + nav.nav_type + Environment.NewLine;
            navMsg = msg;
            meMsg.Text = msg;
        }
        public void iRefresh_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (currentForm != null)
            {
                //if (currentForm.Save)
                if (currentForm.CurrentDsSave)
                {
                    if (this.ShowMessage(this, "当前数据未保存，是否继续？", "", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) == System.Windows.Forms.DialogResult.No)
                        return;
                }

                //SplashScreenManager.ShowForm(this, typeof(SaveSplashScreen), true, true, false);
                //SplashScreenManager.Default.SendCommand(LoadStatus.ShowTitle, "正在抽取数据，请稍候...");
                //SplashScreenManager.Default.SendCommand(LoadStatus.ShowProgress, "正在抽取数据，请稍候...");
                if (currentForm.IsDataSourceQuery())
                {
                    SplashScreenManager.ShowForm(this, typeof(dlgWaitForm), true, true, false);
                    
                    currentForm.CurrentSourceBinding.UserWhere = "";
                    if (currentForm.CurrentSourceBinding.Equals(currentForm.MasterdataSourceBinding))
                    {
                        currentForm.MasterdataSourceBinding.UserWhere = "";
                        //SalWindow.FireWindowActions(currentForm, Const.PM_DataSourceRefresh, 3, currentForm.MasterdataSourceBinding.Identify);
                        currentForm.ResetRefreshTag();
                        currentForm.CurrentSourceBinding.vrtDataSourceRefresh(DataSourcePopulate.RePopulate);
                        currentForm.RefreshDetailByMasterCurrent();

                    }
                    if (currentForm.CurrentSourceBinding.LogicalParent == null && currentForm.CurrentSourceBinding.IsLimit && currentForm.CurrentSourceBinding.Session.RecordCount > currentForm.CurrentSourceBinding.RecordLimit && currentForm.CurrentSourceBinding.RecordLimit > 0)
                    {
                        dlgAskFetch dlgFetch = new dlgAskFetch(currentForm.CurrentSourceBinding.Session.RecordCount, currentForm.CurrentSourceBinding, currentForm);
                        if (dlgFetch.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
                        {
                            SalWindow.FireWindowActions(currentForm, Const.PM_DataSourceRefresh, dlgFetch.FetchMode, currentForm.CurrentSourceBinding.Identify);
                        }
                    }
                    else if (!currentForm.CurrentSourceBinding.Equals(currentForm.MasterdataSourceBinding))
                        SalWindow.FireWindowActions(currentForm, Const.PM_DataSourceRefresh, 2, currentForm.CurrentSourceBinding.Identify);
                    if (currentForm.CurrentSourceBinding.Count > 0)
                        SetToolbarEnable(true);
                    else
                        SetToolbarEnable(false);
                }
                //SplashScreenManager.CloseForm(false);
            }
            this.iSave.Enabled = false;
        }
        private List<fnd_user_profile> currentQProfile;
        private void LoadUserQuery(List<fnd_user_profile> QProfile)
        {
            currentQProfile = QProfile;
            biQueryList.EditValue = "";
            cbQueryList.Items.Clear();
            if (QProfile == null || QProfile.Count == 0)
                return;
            foreach (fnd_user_profile qi in QProfile)
            {

                cbQueryList.Items.Add(qi.description);
            }
        }
        private void tabbedView_DocumentActivated(object sender, DocumentEventArgs e)
        {
            
            currentForm = e.Document.Control as BaseForm;
            if (currentForm.CurrentSourceBinding == null)
                return;
            currentForm.SetMainFunction();
            if (currentForm != null && currentForm.CurrentSourceBinding != null)
            {
                if (currentForm.Save)
                    iSave.Enabled = true;
                else
                    iSave.Enabled = false;
                DispDSBInfo(currentForm.CurrentSourceBinding);
            }
            LoadUserQuery(currentForm.UQProfile);
            SetNewRecordEnable();

            //if (currentForm.CurrentSourceBinding.Updates == Platform.Enums.UpdatesSql.ReadOnly || !currentForm.CurrentSourceBinding.AllowRemove)
            //{
            //    iDelete.Enabled = false;
            //}
            //else
            //{
            //    iDelete.Enabled = currentForm.IsDataSourceDelete();

            //}
            //if (currentForm.CurrentSourceBinding.Updates == Platform.Enums.UpdatesSql.ReadOnly || !currentForm.CurrentSourceBinding.AllowNew)
            //    iNewRecord.Enabled = false;
            //else
            //    iNewRecord.Enabled = currentForm.IsDataSourceNew();
            //if (currentForm != null)
            //{
            //    iApproval.Enabled = ApprovalRouting.ApprovalRouting_IsLuAllow(currentForm.MasterdataSourceBinding.LogicalUnit);
            //    SetApprovalVisible(false);
            //    //GetApprovalEnable(currentForm.CurrentSourceBinding);
            //    //LoadApproval_routing();
            //}

        }
        private void SetApprovalVisible(bool visible)
        {
            DockPanel dp = GetTopDockPanel(dockPanelApproval);
            if (visible)
            {
                dp.Show();
            }
            else
                dp.Hide();
        }
        private bool GetApprovalEnable(DataSourceBinding dsb)
        {
            if (dsb == null)
            {
                iApproval.Enabled = false;
                return iApproval.Enabled;
            }
            DockPanel dp = GetTopDockPanel(dockPanelApproval);

            iApproval.Enabled = ApprovalRouting.ApprovalRouting_IsLuAllow(dsb.LogicalUnit);
            if (iApproval.Enabled == false)
            {

                dp.Hide();
            }
            else
            {
                if (!dsb.Equals(currentForm.MasterdataSourceBinding))
                    dp.Hide();

            }


            return iApproval.Enabled;
        }
        private bool ApprovalVisible()
        {
            return iApproval.Enabled;
        }
        public void iNewRecord_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (currentForm != null)
            {
                if (currentForm.CurrentSourceBinding.Updates == Platform.Enums.UpdatesSql.ReadOnly || !currentForm.CurrentSourceBinding.AllowNew)
                {
                    this.ShowMessage("不允许新增记录");
                    return;
                }

                SalWindow.FireWindowActions(currentForm, Const.PM_DataRecordNew, 1, currentForm.CurrentSourceBinding.Identify);
                if (currentForm.CurrentSourceBinding.Count == 1)
                    currentForm.SetControlReadOnly(currentForm, currentForm.CurrentSourceBinding);
                SalWindow.FireWindowActions(currentForm, Const.PM_DataSourceReBinding, 1, currentForm.CurrentSourceBinding.Identify);
                if (FoucsDataItem != null && FoucsDataItem.GridView != null && FoucsDataItem.GridView is GridView)
                {
                    GridView gview = FoucsDataItem.GridView as GridView;
                    if (gview != null)
                    {
                        gview.ClearSelection();
                    }
                }
                iSave.Enabled = true;
                //tblRouting.DataSource = null;
                //tblRouting.RefreshDataSource();
            }
        }

        private void iSave_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (currentForm != null)
            {

                SalWindow.FireWindowActions(currentForm, Const.PM_DataSourceSave, 1, 0);

            }
        }

        private void iClear_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (this.currentForm != null)
            {
                this.currentForm.ClearCurrentDataExclude(this.currentForm.CurrentSourceBinding);
            }
        }

        public void iQuary_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {

            if (this.currentForm != null)
            {
                //if (this.currentForm.Save)
                if (this.currentForm.CurrentDsSave)
                {
                    if (this.ShowMessage("当前记录还没有保存，是否需要取消？", "", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == System.Windows.Forms.DialogResult.No)
                        return;
                    else
                    {
                        iSave.Enabled = false;
                    }
                }
                string where = currentForm.CurrentSourceBinding.OnDataIsQueryingWhere(currentForm);
                BaseForm queryForm = new frmQuery(this.currentForm, this.currentForm.UQProfile, 0, where, this.currentForm.GetCurrentDSGrid());
                queryForm.ShowDialog();
                LoadUserQuery(currentForm.UQProfile);
            }
        }

        private void iAttach_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {

        }
        public bool EnableSave
        {
            set
            {
                this.iSave.Enabled = value;
            }
        }
        public void iDelete_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {

            if (currentForm != null)
            {
                iDelete.Enabled = currentForm.IsDataSourceDelete();
                if (currentForm.CurrentSourceBinding.Updates == Platform.Enums.UpdatesSql.ReadOnly || !currentForm.CurrentSourceBinding.AllowRemove)
                {
                    this.ShowMessage("不允许删除记录");
                    return;
                }
                if (FoucsDataItem.GridView != null && FoucsDataItem.GridView is GridView)
                {
                    GridView gview = FoucsDataItem.GridView as GridView;
                    if (gview != null)
                    {
                        int[] select = gview.GetSelectedRows();
                        if (select.Length == 0)
                        {
                            this.ShowMessage("没有选中记录，请选择要删除的记录！", "", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                            return;
                        }
                        List<IEntity> list = new List<IEntity>();
                        foreach (int idx in select)
                        {
                            IEntity en = gview.GetRow(idx) as IEntity;
                            list.Add(en);
                        }
                        SalWindow.FireWindowActions(currentForm, Const.PM_DataRecordRemove, list, currentForm.CurrentSourceBinding.Identify);
                        gview.GridControl.RefreshDataSource();
                    }
                }
                else
                {
                    SalWindow.FireWindowActions(currentForm, Const.PM_DataRecordRemove, currentForm.CurrentSourceBinding.Current, currentForm.CurrentSourceBinding.Identify);
                }
                //IEntity entity = null;
                //if (_activeControl != null && _activeControl is cGridControl)
                //{
                //    cGridControl g = _activeControl as cGridControl;
                //    GridView gv = g.MainView as GridView;
                //    entity = gv.GetFocusedRow() as IEntity;
                //}
                //if (currentForm.CurrentSourceBinding.Current == null || !(currentForm.CurrentSourceBinding.Current is Fcdbas.Core.IEntity))
                //    return;

                //IEntity en = currentForm.CurrentSourceBinding.Current as IEntity;
                //if(en != null && entity != null && en["objid"].ToString() == entity["objid"].ToString())
                //    SalWindow.FireWindowActions(currentForm, Const.PM_DataRecordRemove, currentForm.CurrentSourceBinding.Current, currentForm.CurrentSourceBinding.Identify);
                //else if( entity != null)
                //    SalWindow.FireWindowActions(currentForm, Const.PM_DataRecordRemove, entity, currentForm.CurrentSourceBinding.Identify);
                //else
                //iSave.Enabled = true;

                iSave.Enabled = currentForm.Save;
            }
        }

        private void iValueList_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (currentForm == null)
                return;
            if (_currentDataItem != null)
            {
                if (_currentDataItem.LogicalParent != null)
                {
                    string title = _currentDataItem.Caption;
                    bool mulSelect = currentForm.OnLovQueryMultipleSelectioin(FoucsDataItem.DItem);
                    string UserWhere = currentForm.OnDataItemLovUserWhere(FoucsDataItem.DItem);
                    string orderBy = currentForm.OnDataItemLovOrderBy(FoucsDataItem.DItem);
                    frmValueList frmValue = new frmValueList(_currentDataItem.LogicalParent.ToString(), UserWhere, orderBy, title, mulSelect);
                    if (frmValue.ShowDialog(this) == DialogResult.OK)
                    {
                        currentForm.OnDataItemLovDone(FoucsDataItem.DItem, frmValue.SelectEntity);
                        if (currentForm != null && currentForm.CurrentSourceBinding != null && currentForm.CurrentSourceBinding.Current != null)
                        {
                            IEntity en = currentForm.CurrentSourceBinding.Current as IEntity;
                            if (en != null)
                            {
                                string value = frmValue.Key;//frmValue.SelectEntity;
                                if (mulSelect)
                                {
                                    string[] v = value.Split(ClientSys.group_separator_);
                                    if (v.Length > 0)
                                        value = v[0];
                                }
                                // string oValue = en.GetAttr(false);
                                en.EditAttr("");
                                // if (oValue.IndexOf(value) >= 0)
                                //    return;
                                IEntity OldEntity = en.CloneEntity(false);
                                if (!string.IsNullOrEmpty(value))
                                {
                                    //en.SetAttr(value, false);
                                    //只需要填入当前字段
                                    en[FoucsDataItem.DItem.ColumnName] = value;// ClientSys.GetItemValue(FoucsDataItem.DItem.ColumnName.ToUpper(), value);
                                    iSave.Enabled = true;
                                    if (FoucsDataItem.Control != null && FoucsDataItem.Control is Control)
                                        currentForm.FireOnTextChangedEvent(FoucsDataItem.Control as Control);
                                    currentForm.CurrentSourceBinding.ResetCurrentItem();
                                    if (FoucsDataItem.GridView != null && FoucsDataItem.GridView is GridView)
                                    {
                                        GridView gview = FoucsDataItem.GridView as GridView;
                                        if (gview != null)
                                        {
                                            currentForm.SetReference(currentForm.CurrentSourceBinding, gview, ((GridColumn)FoucsDataItem.Control).FieldName);
                                        }
                                        gview.RefreshData();
                                        gview.RefreshEditor(true);
                                    }
                                    if (en.Status == RecordStatus.Normal)
                                    {
                                        en.Status = RecordStatus.Edit;
                                        currentForm.CurrentSourceBinding.OldEntitys.Add(OldEntity);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        private void iExit_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            this.Close();
        }

        private void frmMainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            // string skinName = DevExpress.LookAndFeel.UserLookAndFeel.Default.ActiveSkinName;

            //DevExpress.LookAndFeel.ActiveLookAndFeelStyle style = DevExpress.LookAndFeel.UserLookAndFeel.Default.ActiveStyle;
            bool bClose = false;
            string msg = "";
            foreach (BaseDocument obj in documentsCore.Values)
            {
                if (obj.Control is BaseForm)
                {
                    BaseForm form = obj.Control as BaseForm;
                    if (form.IsSysSave && form.Save)
                    {
                        msg += "窗体:" + form.Text + " 的数据已经修改";
                        msg += "\n";
                        bClose = true;
                    }
                }
            }
            if (bClose)
            {
                if (this.ShowMessage(msg + "\n" + "是否不保存退出系统？", "", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2) == System.Windows.Forms.DialogResult.No)
                {
                    e.Cancel = true;

                    return;
                }
            }

            if (!bClose)
            {
                if (this.ShowMessage("是否关闭当前系统？", "", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == System.Windows.Forms.DialogResult.No)
                {
                    e.Cancel = true;
                    return;
                }
            }
            SplashScreenManager.ShowForm(this, typeof(SaveSplashScreen), true, true, false);
            mainFormPresenter.UserSkin.info = DevExpress.LookAndFeel.UserLookAndFeel.Default.ActiveSkinName;
            if (mainFormPresenter.UserSkin.Status != RecordStatus.Normal)
            {
                FndDAL.UserProfileNew(mainFormPresenter.UserSkin);
            }
            else
            {
                FndDAL.UserProfileModify(mainFormPresenter.UserSkin);
            }
            SplashScreenManager.Default.SendCommand(LoadStatus.ShowProgress, "正在保存最近使用模块");
            mainFormPresenter.SaveRecentModuleToProfile();
            SplashScreenManager.Default.SendCommand(LoadStatus.ShowProgress, "正在保存收藏夹模块");
            mainFormPresenter.SaveFavModuleToProfile();
            SplashScreenManager.Default.SendCommand(LoadStatus.ShowProgress, "正在保存权限数据");
            FndDAL.AddObjectSecurityToDb();
            SplashScreenManager.Default.SendCommand(LoadStatus.ShowProgress, "正在保存模块对象");
            FndDAL.AddPresObjectToDb();
            SplashScreenManager.Default.SendCommand(LoadStatus.ShowProgress, "保存完成，关闭系统！");
            SplashScreenManager.CloseForm(false);
        }

        private void tvNavigator_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (this.tvNavigator.Selection.Count == 0)
                return;
            TreeListNode node = this.tvNavigator.Selection[0];
            if (node == null || node.Tag == null)
                return;
            Biz.fnd_exp_navigator nav = node.Tag as Biz.fnd_exp_navigator;
            if (nav == null)
                return;
            OpenModule(nav);
            //meMsg.Text = "";
            //string msg = "Key: " + nav.nav_key + "\n";
            //msg += "Name: " + nav.nav_name + "\n";
            //msg += "Object: " + nav.pres_object + "\n";
            //msg += "Type: " + nav.nav_type + "\n";
            //meMsg.Text = msg;
            mainFormPresenter.ClickModule(nav);
        }
        private string BuildCondition(DataItem di, string value, string oper, bool bUCase)
        {
            if (di.DataType == typeof(string))
            {
                switch (oper)
                {
                    case "=":

                        if (!bUCase)
                            return "ucase(" + di.ColumnName + ")=ucase('" + value + "')";
                        else
                            return di.ColumnName + " ='" + value + "'";

                    case "%":
                        return di.ColumnName + " LIKE '" + value + "%'";
                    case "!":
                        return di.ColumnName + " IS NULL";
                    case ">":
                        return di.ColumnName + " >'" + value + "'";
                    case "<":
                        return di.ColumnName + " <'" + value + "'";
                    case ">=":
                        return di.ColumnName + " >='" + value + "'";
                    case "<=":
                        return di.ColumnName + " <='" + value + "'";
                    case "!=":
                        return di.ColumnName + " !='" + value + "'";
                    case "..":
                        {
                            string[] s1 = value.Split("..");
                            if (s1.Length >= 2)
                            {
                                return di.ColumnName + " BETWEEN '" + s1[0] + "' AND '" + s1[1] + "'";
                            }
                            else
                                return "ERROR";
                        }
                    case ";":
                        {
                            string[] s2 = value.Split(";");
                            string where = di.ColumnName + " IN ('";
                            foreach (string s in s2)
                            {
                                where += s + "',";
                            }
                            where = where.Remove(where.Length - 1);
                            where += ")";
                            return where;
                        }
                }

            }
            if (di.DataType == typeof(decimal) || di.DataType == typeof(int) || di.DataType == typeof(float))
            {
                switch (oper)
                {
                    case "=":

                        return di.ColumnName + " =" + value + "";

                    case "%":
                        return di.ColumnName + " LIKE '" + value + "%'";
                    case "!":
                        return di.ColumnName + " IS NULL";
                    case ">":
                        return di.ColumnName + " >" + value;
                    case "<":
                        return di.ColumnName + " <" + value;
                    case ">=":
                        return di.ColumnName + " >=" + value;
                    case "<=":
                        return di.ColumnName + " <=" + value;
                    case "!=":
                        return di.ColumnName + " !=" + value;
                    case "..":
                        {
                            string[] s1 = value.Split("..");
                            if (s1.Length >= 2)
                            {
                                return di.ColumnName + " BETWEEN " + s1[0] + " AND " + s1[1];
                            }
                            else
                                return "ERROR";
                        }
                    case ";":
                        {
                            string[] s2 = value.Split(";");
                            string where = di.ColumnName + " IN (";
                            foreach (string s in s2)
                            {
                                where += s + ",";
                            }
                            where = where.Remove(where.Length - 1);
                            where += ")";
                            return where;
                        }
                }

            }
            if (di.DataType == typeof(DateTime))
            {
                string sdate = "", format = "";
                switch (oper)
                {
                    case "=":
                        if (!ConverToStandard(value, ref sdate, ref format))
                            return "ERROR";
                        return di.ColumnName + " = str_to_date('" + sdate + "'," + format + ")";

                    case "%":
                        return di.ColumnName + " LIKE '" + value + "%'";
                    case "!":
                        return di.ColumnName + " IS NULL";
                    case ">":
                        if (!ConverToStandard(value, ref sdate, ref format))
                            return "ERROR";
                        return di.ColumnName + " > str_to_date('" + sdate + "'," + format + ")";
                    case "<":
                        if (!ConverToStandard(value, ref sdate, ref format))
                            return "ERROR";
                        return di.ColumnName + " < str_to_date('" + sdate + "'," + format + ")";
                    case ">=":
                        if (!ConverToStandard(value, ref sdate, ref format))
                            return "ERROR";
                        return di.ColumnName + " >= str_to_date('" + sdate + "'," + format + ")";
                    case "<=":
                        if (!ConverToStandard(value, ref sdate, ref format))
                            return "ERROR";
                        return di.ColumnName + " <= str_to_date('" + sdate + "'," + format + ")";
                    case "!=":
                        if (!ConverToStandard(value, ref sdate, ref format))
                            return "ERROR";
                        return di.ColumnName + " != str_to_date('" + sdate + "'," + format + ")";
                    case "..":
                        {
                            string[] s1 = value.Split("..");
                            string ss2 = "", format2 = "";
                            if (s1.Length >= 2)
                            {
                                if (!ConverToStandard(s1[0], ref sdate, ref format))
                                    return "ERROR";
                                if (!ConverToStandard(s1[1], ref ss2, ref format2))
                                    return "ERROR";

                                return di.ColumnName + " BETWEEN str_to_date('" + sdate + "'," + format + ")" + " AND " + "str_to_date('" + ss2 + "'," + format2 + ")";
                            }
                            else
                                return "ERROR";
                        }
                    case ";":
                        {
                            string[] s2 = value.Split(";");
                            string where = di.ColumnName + " IN (";
                            foreach (string s in s2)
                            {
                                where += s + ",";
                            }
                            where = where.Remove(where.Length - 1);
                            where += ")";
                            return where;
                        }
                }

            }
            return "ERROR";
        }
        private bool ConverToStandard(string date, ref string ldate, ref string format)
        {
            string sdate = date.Trim();
            string[] s1 = sdate.Split(" ");
            string d = "", t = "";
            if (s1.Length >= 2)
            {
                d = s1[0];
                t = s1[1];
            }
            else
            {
                d = sdate;
            }
            if (!string.IsNullOrEmpty(d))
            {
                string[] s2 = d.Split('-');
                if (s2.Length != 3)
                    return false;
                d = s2[0] + "-";
                d = d + (s2[1].Length == 1 ? s2[1].PadLeft(2, '0') : s2[1]);
                d += "-";
                d = d + (s2[2].Length == 1 ? s2[2].PadLeft(2, '0') : s2[2]);
            }
            if (!string.IsNullOrEmpty(t))
            {
                string[] s2 = t.Split(':');
                if (s2.Length > 3)
                    return false;
                else
                    t = t + ":00:00";
                if (s2.Length == 1)
                    t = s2[0] + ":00:00";
                if (s2.Length == 2)
                    t = s2[0] + ":" + s2[1] + ":00";
                if (s2.Length == 3)
                    t = s2[0] + ":" + s2[1] + ":" + s2[2];
            }
            if (string.IsNullOrEmpty(t))
            {
                ldate = d;
                format = "'%Y-%m-%d'";
            }
            else
            {
                ldate = d + " " + t;
                format = "'%Y-%m-%d %H:%i:%s'";
            }
            return true;
        }
        private void iZoom_ItemClick(object sender, ItemClickEventArgs e)
        {
            if (_currentDataItem != null && !string.IsNullOrEmpty(_currentDataItem.Reference))
            {
                if (currentForm != null && currentForm.CurrentSourceBinding != null && currentForm.CurrentSourceBinding.Current != null)
                {
                    IEntity en = currentForm.CurrentSourceBinding.Current as IEntity;
                    string where = BuildCondition(_currentDataItem, en[_currentDataItem.ColumnName].ToString(), "=", true);

                    OpenModule(_currentDataItem.Reference, where);
                }
            }
        }
        public void DisplayFavModuleView(List<fnd_exp_navigator> navs, List<string> fav)
        {

            var nvs = from c in navs
                      from r in fav
                      where c.nav_key == r
                      select c;
            foreach (fnd_exp_navigator nav in nvs)
            {
                if (!mainFormPresenter.IsAvaliable(nav.pres_object))
                    continue;
                TreeListNode cd = tvNavigator.AppendNode(new object[] { nav.win_text }, FavNode, nav);
                if (nav.nav_type == emNavType.FormWindow.ToString())
                    cd.ImageIndex = 9;
                else if (nav.nav_type == emNavType.MastDetail.ToString())
                    cd.ImageIndex = 4;
                else
                    cd.ImageIndex = 7;
                cd.SelectImageIndex = 3;
            }
        }
        private TreeListNode RecentNode;
        public void DisplayRecentModuleView(List<fnd_exp_navigator> navs, List<RecentModule> recs)
        {
            RecentNode = tvNavigator.AppendNode(new object[] { "最近项目", null, null, 5 }, null);
            var nvs = from c in navs
                      from r in recs
                      where c.nav_key == r.nav_key
                      //orderby r.Hint descending
                      orderby r.LastClickTime descending
                      select c;
            foreach (fnd_exp_navigator nav in nvs)
            {
                if (!mainFormPresenter.IsAvaliable(nav.pres_object))
                    continue;
                TreeListNode cd = tvNavigator.AppendNode(new object[] { nav.win_text }, RecentNode, nav);
                if (nav.nav_type == emNavType.FormWindow.ToString())
                    cd.ImageIndex = 9;
                else if (nav.nav_type == emNavType.MastDetail.ToString())
                    cd.ImageIndex = 4;
                else
                    cd.ImageIndex = 7;
                cd.SelectImageIndex = 3;
            }
        }
        protected DockPanel GetTopDockPanelCore(DockPanel panel)
        {
            if (panel.ParentPanel != null) return GetTopDockPanel(panel.ParentPanel);
            else return panel;
        }
        protected DockPanel GetTopDockPanel(DockPanel panel)
        {
            DockPanel floatPanelCandidate = GetTopDockPanelCore(panel);
            if (floatPanelCandidate.Dock == DockingStyle.Float) return floatPanelCandidate;
            else return panel;
        }
        private void iNav_ItemClick(object sender, ItemClickEventArgs e)
        {
            DockPanel dp = GetTopDockPanel(dockPanelNavigator);
            if (dp.Visibility == DockVisibility.Hidden)
                dp.Show();
            else
                dp.Hide();
        }

        public void iCopy_ItemClick(object sender, ItemClickEventArgs e)
        {
            if (currentForm == null || currentForm.CurrentSourceBinding == null || currentForm.CurrentSourceBinding.Current == null)
                return;
            IEntity en = currentForm.CurrentSourceBinding.Current as IEntity;
            if (en == null)
                return;
            string attr = en.GetAttr(false);
            if (string.IsNullOrEmpty(attr))
                return;
            Clipboard.SetText(attr);
            iNewRecord_ItemClick(this, e);
            if (iSave.Enabled)
            {
                if (currentForm == null || currentForm.CurrentSourceBinding == null || currentForm.CurrentSourceBinding.Current == null)
                    return;
                en = currentForm.CurrentSourceBinding.Current as IEntity;
                if (en == null)
                    return;
                if (FoucsDataItem.GridView != null && FoucsDataItem.GridView is GridView)
                {
                    GridView gview = FoucsDataItem.GridView as GridView;
                    if (gview != null)
                    {
                        gview.ClearSelection();
                    }
                }
                attr = Clipboard.GetText();
                Paste(en, attr, currentForm.CurrentSourceBinding);
                currentForm.CurrentSourceBinding.OnDataRecordDuplicate(1);
                currentForm.CurrentSourceBinding.ResetCurrentItem();
            }
            //iPaste.Enabled = true;
        }
        private void Paste(IEntity en, string attr, DataSourceBinding dsb)
        {
            if (string.IsNullOrEmpty(attr))
                return;
            string[] fields = attr.Split(EntityBase.Record_Separator);
            foreach (string field in fields)
            {
                string[] vals = field.Split(EntityBase.Field_Separator);
                if (vals == null || vals.Length != 2)
                {
                    continue;
                    
                }
                DataItem di = dsb.Columns.Find(p => p.ColumnName.ToLower() == vals[0].ToLower());
                if (di != null && (di.Insertable || di.UpdateOption == DataItemUpdate.Allow || (di.UpdateOption == DataItemUpdate.AllowedIfNull && en[vals[0].ToLower()] != null)))
                    en[vals[0].ToLower()] = vals[1];
            }
        }
        private void iPaste_ItemClick(object sender, ItemClickEventArgs e)
        {
            if (currentForm == null || currentForm.CurrentSourceBinding == null || currentForm.CurrentSourceBinding.Current == null)
                return;
            IEntity en = currentForm.CurrentSourceBinding.Current as IEntity;
            if (en == null)
                return;
            string attr = Clipboard.GetText();
            en.SetAttr(attr, false);
            currentForm.CurrentSourceBinding.ResetCurrentItem();
        }

        private void iOption_ItemClick(object sender, ItemClickEventArgs e)
        {
            dlgOptions dlg = new dlgOptions(this);
            if (dlg.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
            {
                this.timerAlarm.Enabled = AppEnvironment.AppOption.AlarmEnable;
                this.timerAlarm.Interval = AppEnvironment.AppOption.AlarmRiseTime * 1000;
            }
        }

        private void iRefresh_ItemClick_1(object sender, ItemClickEventArgs e)
        {
            if (currentForm == null || currentForm.CurrentSourceBinding == null || currentForm.CurrentSourceBinding.Current == null)
                return;
            IEntity en = currentForm.CurrentSourceBinding.Current as IEntity;
            if (en == null)
                return;
            if (en.Status != RecordStatus.Normal)
            {
                if (this.ShowMessage("当前记录还没有保存，是否取消？", "", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.No)
                    return;

            }

            currentForm.CurrentSourceBinding.vrtDataSourceRefresh(DataSourcePopulate.Current);

            en = currentForm.CurrentSourceBinding.Current as IEntity;
            en.Status = RecordStatus.Normal;
            en.Dirtys.Clear();
            en.ClearAdditionalValues();
            currentForm.RefreshDetailByMasterCurrent();
            currentForm.SetRecSelComboBox(true);
            currentForm.SetDeleteStatus(currentForm, false);
            iSave.Enabled = false;
        }

        private void tblRouting_MouseClick(object sender, MouseEventArgs e)
        {
            //if (e.Button.ToString() == "Right")
            //{
            //    this.menuApproval.Show(MousePosition);
            //}
            //if (e.Button.ToString() == "Left")
            //{
            //    List<approval_routing> lsApprovalRounting = ApprovalRouting.DisplayApprovalRouting();
            //    tblRouting.DataSource = lsApprovalRounting;
            //}
        }
        /*
        private void menuItemAddStep_Click(object sender, EventArgs e)
        {
            if (currentForm == null || currentForm.MasterdataSourceBinding == null || currentForm.MasterdataSourceBinding.Current == null)
                return;
            IEntity en = currentForm.MasterdataSourceBinding.Current as IEntity;
            if (en == null)
                return;
            object obj = null;
            try
            {
                PropertyInfoX infoX = PropertyInfoX.Create(en.GetType(), "objid");
                obj = infoX.GetValue(en);
            }
            catch (Exception ex)
            {
            }
            if (obj == null)
                return;
            dlgAddAppRoutingStep fmAddAppRoutingStep = new dlgAddAppRoutingStep(currentForm.MasterdataSourceBinding.LogicalUnit,obj.ToString());
            if (fmAddAppRoutingStep.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                LoadApproval_routing();
            }
        }
        private void LoadApproval_routing()
        {
            //if (!ApprovalVisible())
             //   return;
            if (currentForm == null || currentForm.MasterdataSourceBinding == null || currentForm.MasterdataSourceBinding.Current == null)
                return;
            if (!currentForm.CurrentSourceBinding.Equals(currentForm.MasterdataSourceBinding))
            {
                tblRouting.DataSource = null;
                tblRouting.RefreshDataSource();
                return;
            }
            IEntity en = currentForm.MasterdataSourceBinding.Current as IEntity;
            if (en == null)
                return;
            object obj = null;
            try
            {
                PropertyInfoX infoX = PropertyInfoX.Create(en.GetType(), "objid");
                obj = infoX.GetValue(en);
            }
            catch(Exception ex)
            {
            }
            if (obj == null)
                return;
            dockPanelApproval.Text = ApprovalRouting.ApprovalRouting_GetKeyDesc(currentForm.MasterdataSourceBinding.LogicalUnit, obj.ToString());
            List<approval_routing> lsApprovalRounting = ApprovalRouting.DisplayApprovalRouting(currentForm.MasterdataSourceBinding.LogicalUnit, obj.ToString());

            tblRouting.DataSource = lsApprovalRounting;
            List<person_group> groups = ApprovalRouting.DisplayPersonGroup();
            groups.Add(new person_group() { group_id = "" });
            MasterdataSourceBinding_colGroupId.DataSource = groups;
            List<person_info> persons = ApprovalRouting.DisplayPersonInfo();
            persons.Add(new person_info() { person_id = "" });
            MasterdataSourceBinding_colPersonId.DataSource = persons;
           
        }
        private void menuItemTemplate_Click(object sender, EventArgs e)
        {
            if (currentForm == null || currentForm.MasterdataSourceBinding == null || currentForm.MasterdataSourceBinding.Current == null)
                return;
            IEntity en = currentForm.MasterdataSourceBinding.Current as IEntity;
            if (en == null)
                return;
            object obj = null;
            try
            {
                PropertyInfoX infoX = PropertyInfoX.Create(en.GetType(), "objid");
                obj = infoX.GetValue(en);
            }
            catch (Exception ex)
            {
            }
            if (obj == null)
                return;
            dlgAddApprovalTemplate fmAddApprovalTemplate = new dlgAddApprovalTemplate(currentForm.MasterdataSourceBinding.LogicalUnit,obj.ToString());
            if (fmAddApprovalTemplate.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                LoadApproval_routing();
            }
        }

        private void menuItemApproval_Click(object sender, EventArgs e)
        {
            //List<approval_routing> ilAppRount = this.tblRouting.GetSelectedRows();
            approval_routing ar = this.vwRouting.GetFocusedRow() as approval_routing;

            if (ar == null)
                return;
            string note = "";
            dlgApprovalNote dlg = new dlgApprovalNote ();
            if(dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                note = dlg.ApprovalNote;
            }
            if(ApprovalRouting.ApprovalRouting_DoApproval(ar.key_name, ar.key_ref, ar.step_no, note))
                LoadApproval_routing();
        }

        private void menuItemDelStep_Click(object sender, EventArgs e)
        {
            approval_routing ar = this.vwRouting.GetFocusedRow() as approval_routing;
            if (ar == null)
                return;
            if (this.ShowMessage("你确认你想删除批准的工艺连接吗？", "", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == System.Windows.Forms.DialogResult.Yes)
            {
                if (ApprovalRouting.ApprovalRouting_RemoveStep(ar.key_name, ar.key_ref, ar.step_no))
                    LoadApproval_routing();
            }
        }

        private void menuItemSaveStep_Click(object sender, EventArgs e)
        {
            //approval_routing ar = this.vwRouting.GetFocusedRow() as approval_routing;
            //if (ar == null)
            //    return;
            List<approval_routing> list = tblRouting.DataSource as List<approval_routing>;
            foreach (approval_routing ar in list)
            {
                if (ar.Status == RecordStatus.Normal)
                    continue;

                string attr = "";
                ClientSys.AddToAttr("group_id", ar.group_id, ref attr);
                ClientSys.AddToAttr("person_id", ar.person_id, ref attr);
                ClientSys.AddToAttr("note", ar.note, ref attr);
                ClientSys.AddToAttr("security_checkpoint_req", ar.security_checkpoint_req, ref attr);
                //ar1.group_id = ar.group_id;
                //ar1.person_id = ar.person_id;
                //ar1.note = ar.note;
                //ar1.objversion = ar.objversion;
                //ar1.objid = ar.objid;
                //ar1.security_checkpoint_req = ar.security_checkpoint_req;
                ApprovalRouting.ApprovalRouting_Modify(ar,attr, "DO");
            }
            LoadApproval_routing();
            
        }

        private void menuApproval_Opening(object sender, CancelEventArgs e)
        {
            approval_routing ar = this.vwRouting.GetFocusedRow() as approval_routing;
            if (ar == null)
                return;
            menuItemReject.Enabled = ApprovalRouting.ApprovalRouting_IsAllowReject(ar.key_name, ar.key_ref, ar.step_no);
            menuItemRevise.Enabled = ApprovalRouting.ApprovalRouting_IsAllowRevise(ar.key_name, ar.key_ref, ar.step_no);
            menuItemApproval.Enabled = ApprovalRouting.ApprovalRouting_IsAllowApproval(ar.key_name, ar.key_ref, ar.step_no);
        }

        private void menuItemReject_Click(object sender, EventArgs e)
        {
            approval_routing ar = this.vwRouting.GetFocusedRow() as approval_routing;

            if (ar == null)
                return;
            string note = "";
            dlgApprovalNote dlg = new dlgApprovalNote();
            if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                note = dlg.ApprovalNote;
            }
            if (ApprovalRouting.ApprovalRouting_DoReject(ar.key_name, ar.key_ref, ar.step_no, note))
                LoadApproval_routing();
        }

        private void menuItemRevise_Click(object sender, EventArgs e)
        {
            approval_routing ar = this.vwRouting.GetFocusedRow() as approval_routing;

            if (ar == null)
                return;
            string note = "";
            //dlgApprovalNote dlg = new dlgApprovalNote();
            //if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            //{
            //    note = dlg.ApprovalNote;
            //}
            if (ApprovalRouting.ApprovalRouting_DoRevise(ar.key_name, ar.key_ref, ar.step_no, note))
                LoadApproval_routing();
        }

        

        private void MasterdataSourceBinding_colGroupId_EditValueChanged(object sender, EventArgs e)
        {
            //approval_routing ar = this.vwRouting.GetFocusedRow() as approval_routing;
            //List<person_group> groups = MasterdataSourceBinding_colGroupId.DataSource as List<person_group>;
            //string groupid = MasterdataSourceBinding_colGroupId.OwnerEdit.Text;
            //person_group pg= groups.Find(p => p.group_id == ar.group_id);
            //ar.Reference2 = pg.group_description;
            //tblRouting.RefreshDataSource();
            //ar.Status = RecordStatus.Edit;
            //MasterdataSourceBinding_colGroupId.GetDataSourceValue("group_description",MasterdataSourceBinding_colGroupId.
        }

        private void MasterdataSourceBinding_colPersonId_EditValueChanged(object sender, EventArgs e)
        {
          //  approval_routing ar = this.vwRouting.GetFocusedRow() as approval_routing;
           
        }

        private void vwRouting_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            
        }
       
        private void vwRouting_CellValueChanging(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            approval_routing ar = this.vwRouting.GetFocusedRow() as approval_routing;
            if (e.Column.FieldName == "group_id")
            {

                List<person_group> groups = MasterdataSourceBinding_colGroupId.DataSource as List<person_group>;
                string groupid = e.Value.ToString();
                person_group pg = groups.Find(p => p.group_id == groupid);
                ar.Reference2 = pg.group_description;
                tblRouting.RefreshDataSource();
               // ar.Status = RecordStatus.Edit;
            }
            if (e.Column.FieldName == "person_id")
            {
                string person_id = e.Value.ToString();
                List<person_info> persons = MasterdataSourceBinding_colPersonId.DataSource as List<person_info>;
                person_info pg = persons.Find(p => p.person_id == person_id);
                ar.Reference1 = pg.person_name;
                tblRouting.RefreshDataSource();
               // ar.Status = RecordStatus.Edit;
            }
            ar.Status = RecordStatus.Edit;
           
            
        }
        */
        private void iApproval_ItemClick(object sender, ItemClickEventArgs e)
        {
            //DockPanel dp = GetTopDockPanel(dockPanelApproval);
            //if (dp.Visibility == DockVisibility.Hidden)
            //{

            //    //LoadApproval_routing();
            //    dp.Show();
            //}
            //else
            //    dp.Hide();
            LoadApproval();
        }
        private void LoadApproval()
        {
            var form = mainFormPresenter.LoadForm("App.Person.Message.dll", "App.Person.Message.frmApprovalRouting");
            form.MainForm = this;
            form.TopLevel = false;
            form.Dock = DockStyle.Fill;
            form.FormBorderStyle = FormBorderStyle.None;

            this.dockPanelApproval.Controls.Add(form);
            this.dockPanelApproval.Text = form.Text;
            form.Show();
            GetTopDockPanel(dockPanelApproval).Show();
        }
        private void iTips_ItemClick(object sender, ItemClickEventArgs e)
        {
            LoadNote();
        }
        private void menuNav_Opening(object sender, CancelEventArgs e)
        {
            if (tvNavigator.FocusedNode != null)
            {
                TreeListNode node = tvNavigator.FocusedNode;
                if (node.Expanded)
                {
                    miCollapse.Enabled = true;
                    miExpand.Enabled = false;
                }
                else
                {
                    miCollapse.Enabled = false;
                    miExpand.Enabled = true;
                }
                if (node.Tag != null)
                {
                    if (node.Tag is string && node.Tag.ToString() == "个人收藏")
                    {
                        miPaste.Enabled = bCopyNav;
                    }
                    if (node.Tag is fnd_exp_navigator)
                    {
                        fnd_exp_navigator nav = node.Tag as fnd_exp_navigator;
                        if (nav.key_type != mainFormPresenter.NVA_TYPE_PARENT)
                            miCopy.Enabled = true;
                        else
                            miCopy.Enabled = false;
                    }
                }
                else
                {
                    miPaste.Enabled = false;
                    miCopy.Enabled = false;
                }
                if (node.ParentNode != null && node.ParentNode.Tag != null && node.ParentNode.Tag is string && node.ParentNode.Tag.ToString() == "个人收藏")
                {
                    miFavDelete.Enabled = true;
                }
                else
                    miFavDelete.Enabled = false;
            }
        }

        private void miExpand_Click(object sender, EventArgs e)
        {
            if (tvNavigator.FocusedNode != null)
            {
                tvNavigator.FocusedNode.ExpandAll();
            }
        }

        private void miRefresh_Click(object sender, EventArgs e)
        {
            tvNavigator.ClearNodes();
            mainFormPresenter.DisplayNavigator();
            mainFormPresenter.DisplayRecentModule();
            mainFormPresenter.DisplayFavModule();
        }

        private void miCollapse_Click(object sender, EventArgs e)
        {
            if (tvNavigator.FocusedNode != null)
            {
                tvNavigator.CollapseAll();
            }
        }
        private bool bCopyNav = false;
        private string copyNavFormat = "NAVKEY@";
        private void miCopy_Click(object sender, EventArgs e)
        {
            if (tvNavigator.FocusedNode != null)
            {
                TreeListNode node = tvNavigator.FocusedNode;
                if (node.Tag is fnd_exp_navigator)
                {
                    fnd_exp_navigator nav = node.Tag as fnd_exp_navigator;
                    Clipboard.SetText(copyNavFormat + nav.nav_key);
                    bCopyNav = true;
                }
            }
        }

        private void miPaste_Click(object sender, EventArgs e)
        {
            if (tvNavigator.FocusedNode != null)
            {
                TreeListNode node = tvNavigator.FocusedNode;

                if (node.Tag != null)
                {
                    if (node.Tag is string && node.Tag.ToString() == "个人收藏")
                    {
                        string navKey = Clipboard.GetText();
                        if (navKey.IndexOf(copyNavFormat) < 0)
                            return;
                        navKey = navKey.Replace(copyNavFormat, "");
                        if (mainFormPresenter.FavList.Contains(navKey))
                            return;
                        bCopyNav = false;
                        node.Nodes.Clear();
                        mainFormPresenter.FavList.Add(navKey);
                        mainFormPresenter.DisplayFavModule();
                    }
                }
            }
        }

        private void miReset_Click(object sender, EventArgs e)
        {
            if (this.ShowMessage("将会清除个人收藏和最近打开项目的内容，请确认是否继续？", "", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.No)
                return;
            mainFormPresenter.Reset();
            FavNode.Nodes.Clear();
            RecentNode.Nodes.Clear();
        }

        private void iMisstion_ItemClick(object sender, ItemClickEventArgs e)
        {
            LoadTask();

        }

        private void cbQueryList_SelectedValueChanged(object sender, EventArgs e)
        {


        }

        private void biQueryList_EditValueChanged(object sender, EventArgs e)
        {
            if (currentQProfile == null || currentQProfile.Count == 0)
                return;
            if (biQueryList.EditValue == null)
                return;
            var where = (from c in currentQProfile
                         where c.description == biQueryList.EditValue.ToString()
                         select c).FirstOrDefault();
            if (where != null)
            {
                currentForm.CurrentSourceBinding.UserWhere = where.where_clause;
                currentForm.CurrentSourceBinding.UserOrderBy = where.order_clause;
                currentForm.UserQuery(DataSourcePopulate.RePopulate);
            }
        }

        private void iImformation_ItemClick(object sender, ItemClickEventArgs e)
        {
            LoadMessage();
        }

        private void dockManager1_VisibilityChanged(object sender, VisibilityChangedEventArgs e)
        {
            if (e.OldVisibility == DockVisibility.Visible)
            {
                if (e.Panel.Controls.Count > 0 && e.Panel.Controls[0] is BaseForm)
                {
                    BaseForm frm = e.Panel.Controls[0] as BaseForm;
                    e.Panel.Controls.Clear();
                    frm.Close();
                }
            }
        }

        private void dockPanelDoc_ClosingPanel(object sender, DockPanelCancelEventArgs e)
        {
            DockPanel panel = sender as DockPanel;
            if (panel.Controls.Count == 0)
                return;
            DevExpress.XtraBars.Docking.ControlContainer cc = panel.Controls[0] as DevExpress.XtraBars.Docking.ControlContainer;
            if (cc.Controls.Count == 0)
                return;
            BaseForm frm = cc.Controls[0] as BaseForm;
            if (frm != null)
            {
                TypeX.Delete(frm.GetType());
                cc.Controls.Clear();
                frm.Close();
                frm.Dispose();
            }
        }



        private void iAttch_ItemClick(object sender, ItemClickEventArgs e)
        {
            LoadDocument();
        }

        private void timerAlarm_Tick(object sender, EventArgs e)
        {
            object obj = mainFormPresenter.CreateObject("App.Person.Notes.dll", "App.Person.Notes.NotebookAlarm");
            MethodInfoX method = MethodInfoX.Create(obj.GetType(), "AlarmEventRise");
            method.Invoke(obj);
        }
        private void LoadWorkCenter()
        {
            BaseDocument document = null;
            if (!Documents.TryGetValue("App.Person.Message.frmMyWorkCenter", out document))
            {
                BaseForm baseForm = mainFormPresenter.LoadForm("App.Person.Message.dll", "App.Person.Message.frmMyWorkCenter");

                if (baseForm == null)
                    return;
                baseForm.Tag = "App.Person.Message.frmMyWorkCenter";
                ShowModule(baseForm);
                //if (tabbedView.Documents.TryGetValue(baseForm, out document))
                //{
                //    document.Caption = nav.win_text;
                //    document.Tag = nav;
                //}
            }
            else tabbedView.Controller.Activate(document);
        }

        private void LoadHistoryLog()
        {
            BaseDocument document = null;
            BaseForm PrvForm = currentForm;
            DataSourceBinding prvDs = currentForm.CurrentSourceBinding;
            if (!Documents.TryGetValue("App.Admin.History.frmFndHistoryLog", out document))
            {
                BaseForm baseForm = mainFormPresenter.LoadForm("App.Admin.History.dll", "App.Admin.History.frmFndHistoryLog");

                if (baseForm == null)
                    return;
                baseForm.Tag = "App.Admin.History.frmFndHistoryLog";
                ShowModule(baseForm);
                //if (tabbedView.Documents.TryGetValue(baseForm, out document))
                //{
                //    document.Caption = nav.win_text;
                //    document.Tag = nav;
                //}
            }
            else tabbedView.Controller.Activate(document);
            if (DataSourceChanged != null)
                DataSourceChanged.Invoke(PrvForm, new DataSourceEventArgs(prvDs));
        }
        private void biWorkCenter_ItemClick(object sender, ItemClickEventArgs e)
        {
            LoadWorkCenter();
        }

        private void miFavDelete_Click(object sender, EventArgs e)
        {
            if (tvNavigator.FocusedNode != null)
            {
                TreeListNode node = tvNavigator.FocusedNode;
                if (node.Tag is fnd_exp_navigator)
                {
                    fnd_exp_navigator nav = node.Tag as fnd_exp_navigator;
                    if (!mainFormPresenter.FavList.Contains(nav.nav_key))
                        return;
                    mainFormPresenter.FavList.Remove(nav.nav_key);
                    node.ParentNode.Nodes.Remove(node);
                }
            }
        }

        private void miUpdate_ItemClick(object sender, ItemClickEventArgs e)
        {
            this.Close();
            string updateExe = Fcdbas.Core.Configuration.Config.GetConfig<string>("AutoUpdateExe", "update.exe");
            Process proc = Process.Start(updateExe, "true");
            // Application.Exit();
        }

        private void iNext_ItemClick(object sender, ItemClickEventArgs e)
        {
            if (currentForm == null || currentForm.CurrentSourceBinding == null || currentForm.CurrentSourceBinding.Count == 0)
                return;
            currentForm.CurrentSourceBinding.Session.RecordRefresh = true;
            currentForm.CurrentSourceBinding.MoveNext();
            RefreshDetail();
            currentForm.CurrentSourceBinding.Session.RecordRefresh = false;
        }

        private void iFront_ItemClick(object sender, ItemClickEventArgs e)
        {
            if (currentForm == null || currentForm.CurrentSourceBinding == null || currentForm.CurrentSourceBinding.Count == 0)
                return;
            currentForm.CurrentSourceBinding.Session.RecordRefresh = true;
            currentForm.CurrentSourceBinding.MovePrevious();
            RefreshDetail();
            currentForm.CurrentSourceBinding.Session.RecordRefresh = false;
        }
        private void RefreshDetail()
        {
            IEntity en = currentForm.CurrentSourceBinding.Current as IEntity;
            Dictionary<string, object> keys = new Dictionary<string, object>();
            foreach (DataItem di in currentForm.CurrentSourceBinding.Columns)
            {
                if (!keys.ContainsKey(di.ColumnName) && en[di.ColumnName] != null)
                    keys.Add(di.ColumnName, en[di.ColumnName]);

            }
            Fcdbas.Core.Windows.SalWindow.FireWindowActions(currentForm, Fcdbas.Platform.Const.PM_DataRecordRefresh, currentForm.CurrentSourceBinding, keys);
        }

        private void iChangePassword_ItemClick(object sender, ItemClickEventArgs e)
        {
            dlgChangePassword dlg = new dlgChangePassword();
            dlg.MainForm = this;
            dlg.ShowDialog(this);
        }
        private void CloseAll()
        {
            for (int i = 0; i < tabbedView.Documents.Count; )
            {
                if (tabbedView.Documents[0].Control is BaseForm)
                {
                    BaseForm frm = tabbedView.Documents[0].Control as BaseForm;
                    frm.Close();
                }
            }
        }
        private void iLogon_ItemClick(object sender, ItemClickEventArgs e)
        {
            mainFormPresenter.Init();
            FavNode.Nodes.Clear();
            RecentNode.Nodes.Clear();
            this.Hide();
            LoginForm login = new LoginForm(true);
            if (login.ShowDialog() != DialogResult.No)
            {
                CloseAll();
                this.Init();
                this.Show();
                SetTitle();
            }
            else
                this.Close();

        }

        private void iHistory_ItemClick(object sender, ItemClickEventArgs e)
        {
            LoadHistoryLog();
        }
    }
}